package com.hmdp.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("list")
    public Result queryTypeList() {
//        从Redis中查询，查到则返回，没查到则查询数据库并且存入Redis
        String key = "heima:shopList";
        String shopList = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopList)){
            List<ShopType> shopTypes = JSONUtil.toList(shopList, ShopType.class);
            return Result.ok(shopTypes);
        }


        //Redis没查到，查数据库
        List<ShopType> typeList = typeService
                .query().orderByAsc("sort").list();
//        写入Redis并且返回，以字符串格式存入Redis
        String jsonStr = JSONUtil.toJsonStr(typeList);
        stringRedisTemplate.opsForValue().set(key,jsonStr);
        //从Redis中取数据
        String duquList = stringRedisTemplate.opsForValue().get(key);
        //把数据存入Redis
        return Result.ok(typeList);
    }
}
